package net.fruit.mq.client.internal;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 路径类工具
 * 
 * @author CnJun
 */
public class PathUtil {
	private static Logger log = LoggerFactory.getLogger(PathUtil.class);
	
	public static String basePath;//程序根目录
	public static String userDir;//
	public static String tempDir;
	public static boolean isWeb;
	
	static {
		basePath = decode(getBasePath());
		userDir = decode(getUserDir());
		tempDir = decode(getTempDir());
	}
	
	private static String decode(String path) {
		String result = path;
		try {
			result = URLDecoder.decode(path, Charset.defaultCharset().toString());
		} catch (Exception e) {
			result = path.replaceAll("%20", " ");
		}
		return result;
	}
	
	private static String getTempDir() {
		String user_dir = System.getProperty("java.io.tmpdir").replace("\\", "/");
		
		if (!user_dir.endsWith("/")) {
			user_dir += "/";
		}
		
		return user_dir;
	}
	
	private static String getUserDir() {
		String user_dir = System.getProperty("user.dir").replace("\\", "/");
		
		if (!user_dir.endsWith("/")) {
			user_dir += "/";
		}
		
		return user_dir;
	}
	
	private final static String getBasePath() {
		String base = "";
		URL url = PathUtil.class.getResource("/");
		
		if (url != null) {
			base = url.getFile();
			if (base.endsWith("/classes") || base.endsWith("classes/")) {
			} else {
			    String jarFilePath = PathUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile();
		        try {
		            jarFilePath = java.net.URLDecoder.decode(jarFilePath, "UTF-8");
		        } catch (UnsupportedEncodingException e1) {
		        }
		        base = new File(jarFilePath).getParent();
		        if (base.startsWith("/") && base.charAt(2) == ':') {
		            base = base.substring(1);
		        }
			}
		} else {
			base = getUserDir();
		}
		try {
			File file = new File(base);
			while (true) {
				base = file.getCanonicalPath();
				if (base.endsWith(File.separator + "classes") 
						|| base.endsWith(File.separator + "WEB-INF") 
						|| base.endsWith(File.separator + "test-classes")
						|| base.endsWith(File.separator + "target")
						|| base.endsWith(File.separator + "lib")
						|| base.endsWith(File.separator + "bin")) {
					file = file.getParentFile();
				} else {
					break;
				}
			}
			
			base += File.separator;
			
			File web_inf = new File(base + "WEB-INF");
			if (web_inf.exists()) {
				isWeb = true;
			} else {
				isWeb = false;
			}
		} catch (IOException e) {
			log.error("get base path failture, {}", e.getMessage());
			throw new RuntimeException(e);
		}
		
		return base;
	}
}
